<?php

namespace App\Plugins\Wechat;

use App\Models\Customer;
use Illuminate\Support\Facades\Redis;

class Messages
{
    protected $_uin;
    protected $_error = '';
    /**
     * @var \MongoDB\Collection $_db
     */
    protected $_db;

    protected $_message;

    public function __construct($uinOrMessage)
    {
        if (is_array($uinOrMessage)) {
            $this->_initByMessage($uinOrMessage);
        } else if (is_numeric($uinOrMessage)) {
            $this->_initByUin($uinOrMessage);
        } else {
            $this->_error = 'init data fault!';
        }
    }

    protected function _initByUin($uin)
    {
        $this->_uin = intval($uin);
        $this->_db = DB::createDb($uin);
    }

    protected function _initByMessage(Array $message)
    {
        $this->_uin = array_get($message, 'clientUin', null);
        if (is_null($this->_uin)) {
            $this->_error = 'not valid uin';
            return;
        }
        $this->_message = $message;
    }

    /**
     * 查询接收过消息
     * @param $filters
     * @return int
     */
    public function isMessage($filters){
        $filters = array_merge(['clientUin' => strval($this->_uin)], $filters);
        $total = $this->_db->count($filters);
        return $total;
    }


    public function getError()
    {
        return $this->_error;
    }
}